package com.intelli.eve.core.impl.io.local;

import com.intelli.eve.Eve;
import com.intelli.eve.core.api.message.Message;
import com.intelli.eve.core.api.message.MessageProtocols;
import com.intelli.eve.core.api.message.Receiver;
import com.intelli.ray.core.ManagedComponent;

import javax.annotation.Nonnull;
import java.lang.reflect.InvocationTargetException;

/**
 * Author: Sergey42
 * Date: 21.12.2014 19:29
 */
@ManagedComponent(name = "ComponentReceiver")
public class ComponentReceiver implements Receiver {

    @Nonnull
    @Override
    public String getProtocol() {
        return MessageProtocols.MANAGED_COMPONENT;
    }

    @Override
    public void handle(@Nonnull Message message) {
        SystemMessage systemMessage = (SystemMessage) message;
        ComponentInvocationInfo invocationInfo = systemMessage.getComponentInvocationInfo();

        String componentName = invocationInfo.getComponentName();
        String methodName = invocationInfo.getMethodName();

        Object component = Eve.getContext().getBean(componentName);
        Object[] args = invocationInfo.getArgs();
        Class[] argTypes = invocationInfo.getArgTypes();

        try {
            component.getClass().getMethod(methodName, argTypes).invoke(component, args);
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
